﻿using QuanLyChoVayCaNhan.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace QuanLyChoVayCaNhan.Classes
{
    public class UserManager
    {
        private static UserManager INSTANCE = new UserManager();

        public static UserManager GetInstance()
        {
            return INSTANCE;
        }

        private NhanVien user = null;
        
        private MD5 md5 = MD5.Create();
        public bool IsLoggedIn()
        {
            return user != null;
        }
        
        public bool Login(string maNV, string password)
        {
            string hashPassword = getMd5FromString(password);
            user = ModelManager.GetInstance().db.NhanViens.FirstOrDefault<NhanVien>((x) => x.MaNV == maNV && x.Password == hashPassword);
            return IsLoggedIn();
        }

        public string getMd5FromString(string password)
        {
            byte[] hashCode = md5.ComputeHash(Encoding.Unicode.GetBytes(password));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashCode.Length; i++)
            {
                sb.Append(hashCode[i].ToString("x2"));
            }
            return sb.ToString();
        }

        public int GetGroupID()
        {
            if (user == null) return -1;
            return user.GroupID;
        }

        // co phai admin
        public bool IsAdmin()
        {
            return GetGroupID() == 1;
        }

        // co phai can bo quan he khach hang
        public bool IsCBQHKH()
        {
            return GetGroupID() == 2;
        }

        // co phai can bo tham dinh tin dung
        public bool IsCBTDTD()
        {
            return GetGroupID() == 3;
        }

        // co phai can bo ho tro quan he khach hang
        public bool IsCBHTQHKH()
        {
            return GetGroupID() == 4;
        }

        public string GetMaNhanVien()
        {
            return user.MaNV;
        }

        public NhanVien GetNhanVien()
        {
            return user;
        }

        internal void Logout()
        {
            user = null;
        }
    }
}
